package com.chen.music.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.music.model.*;
import com.chen.music.service.*;
import com.chen.music.util.CommonResult;
import com.chen.music.util.MessageConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * <p>
 * 歌单 前端控制器
 * </p>
 *
 * @author boat
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/songList")
@Api(tags = "歌单管理")
public class SongListController {

    @Autowired
    private SongService songService;

    @Autowired
    private SongListService songListService;

    @Autowired
    private ListSongService listSongService;

    @Autowired
    private RankService rankService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CollectService collectService;

    @PostMapping("/add")
    @ApiOperation("新增歌单")
    public CommonResult add(SongList songList) {
        try {
            if (songListService.save(songList)) {
                return new CommonResult(200, true, MessageConst.ADD_SONG_LIST_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.ADD_SONG_LIST_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/{currentPage}/{pageSize}")
    @ApiOperation("歌单检索")
    public CommonResult findByPageAndParam(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize, SongList songList) {
        try {
            Page<SongList> page = songListService.page(new Page<>(currentPage, pageSize), getWrapper(songList));
            if (currentPage > page.getPages()) { //判断当前也是否大于总页数
                return new CommonResult(200, true, songListService.page(new Page<>(page.getPages(), pageSize), getWrapper(songList)));
            }
            return new CommonResult(200, true, songListService.page(new Page<>(currentPage, pageSize), getWrapper(songList)));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PutMapping("/update")
    @ApiOperation("更新歌单")
    public CommonResult update(SongList songList) {
        try {
            if (songListService.updateById(songList)) {
                return new CommonResult(200, true, MessageConst.UPDATE_SONG_LIST_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_LIST_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @DeleteMapping("/delete/{idx}")
    @ApiOperation("删除歌单")
    public CommonResult delete(@PathVariable("idx") String ids) {
        try {
            for (String id : Arrays.asList(ids)) {
                SongList songList = songListService.getById(Integer.parseInt(id));
                File picFile = new File(System.getProperty("user.dir") + songList.getPic());
                Map<String, Object> map = new HashMap<>();
                map.put("song_list_id", Integer.parseInt(id));
                List<Rank> ranks = rankService.listByMap(map);
                if (ranks != null && ranks.size() > 0) {
                    rankService.removeByMap(map);
                }
                List<Comment> comments = commentService.listByMap(map);
                if (comments != null && comments.size() > 0) {
                    commentService.removeByMap(map);
                }
                List<Collect> collects = collectService.listByMap(map);
                if (collects != null && collects.size() > 0) {
                    collectService.removeByMap(map);
                }
                if (listSongService.removeByMap(map) && songListService.removeById(id)) {
                    if (picFile.exists()) {
                        picFile.delete();
                    }
                }
            }
            return new CommonResult(200, true, MessageConst.DELETE_SONG_LIST_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.DELETE_SONG_LIST_FAIL);
        }
    }

    @PostMapping("/update/{id}")
    @ApiOperation("更新歌单图片")
    public CommonResult updateImg(@RequestParam("file") MultipartFile multipartFile, @PathVariable("id") Integer id) {
        if (multipartFile.isEmpty()) {
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_LIST_IMG_FAIL);
        }
        String fileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator")
                + "songListPic"; //文件路径
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        //上传后的文件地址
        File realPath = new File(filePath + System.getProperty("file.separator") + fileName);
        try {
            multipartFile.transferTo(realPath);
            SongList songList = songListService.getById(id);
            //删除原文件
            File picFile = new File(System.getProperty("user.dir") + songList.getPic());
            if (picFile.exists()) {
                picFile.delete();
            }
            songList.setPic("/img/songListPic/" + fileName); //更新数据库文件的相对地址
            if (songListService.updateById(songList)) {
                return new CommonResult(200, true, MessageConst.UPDATE_SONG_LIST_IMG_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_IMG_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }


    @GetMapping("/detail/{id}/{currentPage}/{pageSize}")
    @ApiOperation("检索指定id歌单包含的歌曲信息")
    public CommonResult findById(@PathVariable("id") Integer id, @PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize,
                                 Song song) {
        try {
            LambdaQueryWrapper<ListSong> wrapper = Wrappers.lambdaQuery();
            wrapper.select(ListSong::getSongId).eq(id != null, ListSong::getSongListId, id);
            List<Integer> songs = new ArrayList<>();
            for (ListSong listSong : listSongService.list(wrapper)) {
                songs.add(listSong.getSongId());
            }
            LambdaQueryWrapper<Song> songWrapper = Wrappers.lambdaQuery();
            songWrapper.in(songs.size() > 0, Song::getId, songs);
            songWrapper.like(!StringUtils.isEmpty(song.getName()), Song::getName, song.getName());
            songWrapper.like(!StringUtils.isEmpty(song.getIntroduction()), Song::getIntroduction, song.getIntroduction());
            Page<Song> page = songService.page(new Page<>(currentPage, pageSize), songWrapper);
            if (currentPage > page.getPages()) {
                return new CommonResult(200, true, songService.page(new Page<>(page.getPages(), pageSize), songWrapper));
            }
            return new CommonResult(200, true, songService.page(new Page<>(currentPage, pageSize), songWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PostMapping("/add/{songId}/{songListId}")
    @ApiOperation("新增歌单歌曲")
    public CommonResult addSong(@PathVariable("songId") Integer songId, @PathVariable("songListId") Integer songListId) {
        try {
            if (listSongService.save(new ListSong(null, songId, songListId))) {
                return new CommonResult(200, true, MessageConst.ADD_LIST_SONG_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.ADD_LIST_SONG_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @DeleteMapping("/delete/{songListId}/{songId}")
    @ApiOperation("删除歌单歌曲")
    public CommonResult delete(@PathVariable("songListId") Integer songListId, @PathVariable("songId") Integer songId) {
        try {
            LambdaQueryWrapper<ListSong> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(songListId != null, ListSong::getSongListId, songListId);
            wrapper.eq(songId != null, ListSong::getSongId, songId);
            if (listSongService.remove(wrapper)) {
                return new CommonResult(200, true, MessageConst.DELETE_LIST_SONG_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.DELETE_LIST_SONG_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping
    @ApiOperation("获取所有歌单信息")
    public CommonResult count() {
        try {
            return new CommonResult(200, true, songListService.list());
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/{style}")
    @ApiOperation("根据风格获取歌单信息")
    public CommonResult count(@PathVariable("style") String style) {
        try {
            LambdaQueryWrapper<SongList> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(!StringUtils.isEmpty(style), SongList::getStyle, style);
            return new CommonResult(200, true, songListService.list(wrapper));
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/search/{param}")
    @ApiOperation("前台歌单检索")
    public CommonResult search(@PathVariable("param") String param) {
        try {
            LambdaQueryWrapper<SongList> wrapper = Wrappers.lambdaQuery();
            wrapper.like(!StringUtils.isEmpty(param), SongList::getTitle, param).or().like(!StringUtils.isEmpty(param), SongList::getStyle, param);
            return new CommonResult(200, true, songListService.list(wrapper));
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("根据id获取歌单详情")
    public CommonResult findById(@PathVariable("id") Integer id) {
        try {
            LambdaQueryWrapper<ListSong> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(id != null, ListSong::getSongListId, id);
            return new CommonResult(200, true, listSongService.list(wrapper));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    //封装查询条件
    private LambdaQueryWrapper<SongList> getWrapper(SongList songList) {
        LambdaQueryWrapper<SongList> wrapper = Wrappers.lambdaQuery();
        wrapper.like(!StringUtils.isEmpty(songList.getTitle()), SongList::getTitle, songList.getTitle());
        wrapper.like(!StringUtils.isEmpty(songList.getStyle()), SongList::getStyle, songList.getStyle());
        return wrapper;
    }
}

